<template>
  <view class="container">
    <!-- 搜索框 -->
    <view class="search-wrapper">
      <view class="search-box">
        <uni-icons type="search" size="18" color="#999"></uni-icons>
        <input type="text" v-model="searchKey" placeholder="搜索文章" placeholder-class="placeholder" confirm-type="search"
          @confirm="goToSearch" />
        <view class="search-btn" @tap="goToSearch">搜索</view>
      </view>
    </view>

    <!-- 标签九宫格 -->
    <view class="tags-grid" v-if="tags.length > 0">
      <view class="tags-container">
        <view class="tag-item" v-for="(tag, index) in tags" :key="index" @tap="goToTagPosts(tag)">
          <view class="tag-content">
            <text class="tag-name">{{ tag.name }}</text>
            <text class="tag-count">{{ tag.count }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 文章列表 -->
    <view class="article-list" v-if="articleList.length > 0">
      <view class="article-item" v-for="(article, index) in articleList" :key="index" @tap="goToDetail(article)">
        <view class="article-content">
          <image class="article-image" :src="article.imageUrl" mode="aspectFill" lazy-load />
          <view class="article-info">
            <text class="title">{{ formatTitle(article.title.rendered) }}</text>
            <rich-text class="desc" :nodes="formatContent(article.excerpt.rendered)"></rich-text>
            <view class="meta-info">
              <text class="date">{{ formatDate(article.date) }}</text>
              <view class="category-tags" v-if="article.categories && article.categories.length">
                <text class="category-tag" v-for="(catId, idx) in article.categories" :key="idx"
                  v-if="getCategoryName(catId)">
                  {{ getCategoryName(catId) }}
                </text>
              </view>
            </view>
            <view class="read-more-btn">
              <text>阅读全文</text>
              <uni-icons type="right" size="14" color="#007AFF"></uni-icons>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view class="loading-box" v-if="loading">
      <view class="loading">
        <view class="loading-spinner"></view>
        <text>加载中...</text>
      </view>
    </view>

    <!-- 没有更多 -->
    <view class="no-more" v-if="noMore && articleList.length > 0">
      <text>没有更多内容了</text>
    </view>

    <!-- 返回顶部按钮 -->
    <view class="back-to-top" v-if="showBackToTop" @tap="backToTop">
      <uni-icons type="top" size="20" color="#fff"></uni-icons>
    </view>
  </view>
</template>

<script>
import api from '@/api/wordpress'

export default {
  data() {
    return {
      searchKey: '',
      articleList: [],
      page: 1,
      loading: false,
      noMore: false,
      defaultImage:
        'https://lzphy.top/wp-content/uploads/2024/11/wp_editor_md_ab8de7ba3b3b6cd27c2957f95aab644a.jpg',
      categories: {},
      showBackToTop: false, // 控制返回顶部按钮的显示
      scrollTop: 0, // 记录滚动位置
      tags: [], // 添加标签数组
    }
  },
  async onLoad() {
    await Promise.all([
      this.getCategories(),
      this.getTags() // 添加获取标签
    ])
    this.getArticles()
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.refreshList()
  },
  // 触底加载
  onReachBottom() {
    if (!this.loading && !this.noMore) {
      this.page++
      this.getArticles()
    }
  },
  // 添加页面滚动监听
  onPageScroll(e) {
    // 当滚动超过 500px 时显示返回顶部按钮
    this.showBackToTop = e.scrollTop > 500
    this.scrollTop = e.scrollTop
  },
  methods: {
    // 刷新列表
    async refreshList() {
      this.page = 1
      this.noMore = false
      this.articleList = []

      // 先重新获取分类信息
      await this.getCategories()
      // 再获取文章列表
      await this.getArticles()

      uni.stopPullDownRefresh()
    },

    // 跳转到搜索页面
    goToSearch() {
      const keyword = this.searchKey.trim()
      if (keyword) {
        uni.navigateTo({
          url: `/pages/search/search?keyword=${encodeURIComponent(keyword)}`
        })
        // 清空搜索框
        this.searchKey = ''
      } else {
        uni.showToast({
          title: '请输入搜索内容',
          icon: 'none'
        })
      }
    },

    // 获取文章列表
    async getArticles() {
      if (this.loading || (this.noMore && this.page > 1)) return

      this.loading = true
      try {
        // 如果是第二页及以后，且categories为空，则重新获取分类
        if (this.page > 1 && Object.keys(this.categories).length === 0) {
          await this.getCategories()
        }

        const res = await api.getArticles(this.page, 10)
        if (res.statusCode === 200 && res.data) {
          const articles = res.data.map(article => ({
            ...article,
            imageUrl: api.getPostImage(article),
            categories: article.categories || []
          }))

          if (this.page === 1) {
            this.articleList = articles
          } else {
            this.articleList = [...this.articleList, ...articles]
          }

          if (articles.length < 10) {
            this.noMore = true
          }
        }
      } catch (e) {
        console.error('获取文章错误:', e)
        uni.showToast({
          title: '获取文章失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    // 格式化标题
    formatTitle(title) {
      return title
        .replace(/&#8211;/g, '-')
        .replace(/&amp;/g, '&')
        .replace(/&#8220;/g, '"')
        .replace(/&#8221;/g, '"')
        .replace(/&#8216;/g, "'")
        .replace(/&#8217;/g, "'")
    },

    // 格式化内容
    formatContent(content) {
      return content
        .replace(/<[^>]+>/g, '')
        .replace(/&nbsp;/g, ' ')
        .replace(/&hellip;/g, '...')
    },

    // 格式化日期
    formatDate(date) {
      const d = new Date(date)
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(
        2,
        '0'
      )}-${String(d.getDate()).padStart(2, '0')}`
    },

    // 跳转到详情页
    goToDetail(article) {
      // console.log('点击文章ID:', article.id)
      uni.navigateTo({
        url: `/pages/detail/detail?id=${article.id}&title=${encodeURIComponent(
          article.title.rendered
        )}`
      })
    },

    // 获取分类列表
    async getCategories() {
      try {
        const res = await api.getCategories()
        if (res.statusCode === 200 && res.data) {
          const categoriesObj = {}
          res.data.forEach(cat => {
            categoriesObj[cat.id] = cat.name
          })
          this.categories = categoriesObj
        }
      } catch (e) {
        console.error('获取分类失败:', e)
      }
    },

    // 获取分类名称
    getCategoryName(catId) {
      return this.categories[catId] || ''  // 如果找不到分类返回空字符串
    },

    // 添加返回顶部方法
    backToTop() {
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 300
      })
    },

    // 获取标签列表
    async getTags() {
      try {
        const res = await api.getTags()
        if (res.statusCode === 200 && res.data) {
          // 只取前9个标签
          this.tags = res.data.slice(0, 9)
        }
      } catch (e) {
        console.error('获取标签失败:', e)
      }
    },

    // 跳转到标签文章列表
    goToTagPosts(tag) {
      uni.navigateTo({
        url: `/pages/tag/posts?id=${tag.id}&name=${encodeURIComponent(tag.name)}`
      })
    },
  }
}
</script>

<style scoped>
.container {
  padding: 15px;
  background-color: #f2f4f8;
  min-height: 100vh;
}

.search-wrapper {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.search-box {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 25px;
  padding: 5px 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  width: 85%;
}

.search-box uni-icons {
  margin-right: 10px;
}

.search-box input {
  flex: 1;
  border: none;
  font-size: 16px;
  color: #333;
  background: transparent;
  padding: 0;
}

.search-box input:focus {
  outline: none;
}

.search-btn {
  background-color: #ff5722;
  color: white;
  padding: 6px 14px;
  border-radius: 25px;
  font-size: 14px;
  margin-left: 8px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.search-btn:hover {
  background-color: #e64a19;
}

.article-list {
  display: flex;
  flex-direction: column;
}

.article-item {
  background: #fff;
  border-radius: 12px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.article-content {
  display: flex;
  padding: 12px;
}

.article-image {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  object-fit: cover;
}

.article-info {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  padding: 10px 15px;
}

.meta-info {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.date {
  font-size: 12px;
  color: #999;
}

.category-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  /* 减小间距 */
}

.category-tag {
  font-size: 12px;
  color: #ff5722;
  background-color: rgba(255, 87, 34, 0.1);
  padding: 2px 6px;
  /* 减小内边距 */
  border-radius: 10px;
  white-space: nowrap;
  /* 防止文字换行 */
}

.title {
  font-size: 16px;
  font-weight: bold;
  line-height: 1.4;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.desc {
  font-size: 13px;
  color: #666;
  line-height: 1.5;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.read-more-btn {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  color: #ff5722;
  font-size: 14px;
}

.read-more-btn text {
  margin-right: 4px;
}

.loading-box {
  padding: 20px 0;
  text-align: center;
}

.loading-spinner {
  width: 30px;
  height: 30px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #ff5722;
  border-radius: 50%;
  margin-bottom: 10px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.no-more {
  text-align: center;
  font-size: 16px;
  color: #999;
  margin-top: 20px;
}

/* 添加返回顶部按钮样式 */
.back-to-top {
  position: fixed;
  right: 20px;
  bottom: 80px;
  width: 40px;
  height: 40px;
  background-color: #ff5722;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(255, 87, 34, 0.3);
  z-index: 999;
  transition: all 0.3s ease;
}

.back-to-top:active {
  transform: scale(0.95);
  background-color: #f4511e;
}

/* 标签九宫格样式 */
.tags-grid {
  margin-bottom: 20px;
  background: #fff;
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  padding: 5px;
}

.tag-item {
  flex: 0 0 calc(33.33% - 8px);
  /* 每行3个，减去间距 */
}

.tag-content {
  background: #f5f6fa;
  border-radius: 12px;
  padding: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 6px;
  transition: all 0.3s ease;
}

.tag-content:active {
  transform: scale(0.95);
  background: #f0f1f5;
}

.tag-name {
  font-size: 14px;
  color: #333;
  text-align: center;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.tag-count {
  font-size: 12px;
  color: #ff5722;
  background: rgba(255, 87, 34, 0.1);
  padding: 2px 8px;
  border-radius: 10px;
  min-width: 20px;
  text-align: center;
}
</style>
